package com.chinaedu.oc.action.productline;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.chinaedu.oc.action.base.BaseController;
import com.chinaedu.oc.action.common.DropDownListAction;
import com.chinaedu.oc.bo.ProductQuery;
import com.chinaedu.oc.constant.Constant;
import com.chinaedu.oc.context.Common.Session;
import com.chinaedu.oc.entity.common.Area;
import com.chinaedu.oc.entity.common.CodeList;
import com.chinaedu.oc.entity.common.Grade;
import com.chinaedu.oc.entity.common.Level;
import com.chinaedu.oc.entity.common.Specialty;
import com.chinaedu.oc.entity.common.System;
import com.chinaedu.oc.entity.manageuser.ManageUser;
import com.chinaedu.oc.po.dto.PubOutputDto;
import com.chinaedu.oc.po.product.Product;
import com.chinaedu.oc.po.product.ProductArea;
import com.chinaedu.oc.po.product.dto.ProductInput;
import com.chinaedu.oc.po.product.dto.QueryProductInput;
import com.chinaedu.oc.po.product.dto.QueryProductOutput;
import com.chinaedu.oc.po.productline.ProductLine;
import com.chinaedu.oc.service.cache.ProductLineCacheServ;
import com.chinaedu.oc.service.cache.StaticCacheServ;
import com.chinaedu.oc.uri.IName;
import com.chinaedu.oc.util.common.CheckParamException;
import com.chinaedu.oc.util.common.JsonUtil;
import com.chinaedu.oc.util.common.StringUtil;
import com.chinaedu.oc.util.csv.CsvCreater;
import com.chinaedu.oc.util.excel.ExcelCreater;
import com.chinaedu.oc.util.http.HttpHelper;
import com.chinaedu.oc.util.http.HttpRequestException;
import com.chinaedu.oc.vo.Code;
import com.chinaedu.oc.vo.CommonListVo;
import com.chinaedu.oc.vo.QueryProduct;

@Controller
@RequestMapping("/product")
public class ProductAction extends BaseController{

	@Autowired
	StaticCacheServ cacheServ;
	@Autowired
	ProductLineCacheServ productLineCacheServ;

	/**
	 * 查询
	 * @Description: TODO
	 * @param @param productQuery
	 * @param @param start
	 * @param @param length
	 * @param @param response
	 * @param @throws HttpRequestException
	 * @return void    返回类型
	 * @throws
	 */
	@RequestMapping("/query")
	@ResponseBody
	public CommonListVo<QueryProduct> query(ProductQuery productQuery,Integer start, Integer length, HttpServletRequest request) throws HttpRequestException{

		CommonListVo<QueryProduct> vo = new CommonListVo<QueryProduct>();


		if(Constant.QUERY_ALL.equals(productQuery.getProductLine())){
			productQuery.setProductLine(null);
		}
		if(Constant.QUERY_ALL.equals(productQuery.getProductType())) {
			productQuery.setProductType(null);
		}
		if(Constant.QUERY_ALL.equals(productQuery.getSchoolSystem())) {
			productQuery.setSchoolSystem(null);
		}
		if(Constant.QUERY_ALL.equals(productQuery.getSchoolLevel())) {
			productQuery.setSchoolLevel(null);
		}
		if(Constant.QUERY_ALL.equals(productQuery.getGrade())) {
			productQuery.setGrade(null);
		}
		if(Constant.QUERY_ALL.equals(productQuery.getSpecialty())) {
			productQuery.setSpecialty(null);
		}
		if(Constant.QUERY_ALL.equals(productQuery.getBillType())) {
			productQuery.setBillType(null);
		}
		if(Constant.QUERY_ALL.equals(productQuery.getBusinessType())) {
			productQuery.setBusinessType(null);
		}
		if(Constant.QUERY_ALL.equals(productQuery.getReviewStatus())) {
			productQuery.setReviewStatus(null);
		}


		String[] areas = request.getParameterValues("area[]");
		if(areas != null) {
			String ar = "";
			for(String s : areas) {
				ar += s + ",";
			}
			ar = ar.substring(0, ar.length()-1);
			productQuery.setAreas(ar);
		}


		//加f_
		if(!StringUtil.isBlack(productQuery.getOrderName())) {
			String orderName = "";
			orderName = productQuery.getOrderName();

			productQuery.setOrderName("f_"+StringUtil.underscoreName(orderName));
		}

		QueryProductInput input = new QueryProductInput();
		input.setProductQuery(productQuery);
		input.setStart(start);
		input.setLength(length);
		QueryProductOutput out = HttpHelper.sendRequest(IName.Product.QUERY_PRODUCT, input, QueryProductOutput.class);
		List<Product> listProduct = out.getListProduct();

		List<QueryProduct> data = new ArrayList<>();
		for(Product p : listProduct) {
			QueryProduct qp = JsonUtil.toBean(JsonUtil.toJsonString(p), QueryProduct.class);
			//业务类型
			CodeList code = cacheServ.queryData(Constant.BUSINESS_TYPE, p.getBusinessType(), CodeList.class);
			qp.setBusinessType(code==null?"":code.getValue());
			//学制
			System sys = cacheServ.queryData(Constant.SCHOOL_SYSTEM, p.getSchoolSystem(), System.class);
			qp.setSchoolSystem(sys==null?"":sys.getSystemName());
			//年级
			Grade g = cacheServ.queryData(Constant.SCHOOL_GRADE, p.getSchoolLevel(), p.getGrade(), Grade.class);
			qp.setGrade(g==null?"":g.getGradeName());
			//学科
			Specialty sp = cacheServ.queryData(Constant.SCHOOL_SPECIALTY, p.getSchoolLevel(), p.getSpecialty(), Specialty.class);
			qp.setSpecialty(sp==null?"":sp.getSpecialtyName());
			//支付方式
			code = cacheServ.queryData(Constant.BILL_TYPE, p.getBillType(), CodeList.class);
			qp.setBillType(code==null?"":code.getValue());
			//转义学段
			Level level = cacheServ.queryData(Constant.SCHOOL_LEVEL, p.getSchoolLevel(), Level.class);
			qp.setSchoolLevel(level==null?"":level.getLevelName());
			//转义产品类型
			code = cacheServ.queryData(Constant.PRODUCT_TYPE, p.getProductType(), CodeList.class);
			qp.setProductType(code==null?"":code.getValue());
			//部门
			code = cacheServ.queryData(Constant.DEPARTMENT, p.getDepartment(), CodeList.class);
			qp.setDepartment(code==null?"":code.getValue());
			//单位
			code = cacheServ.queryData(Constant.UNIT, p.getUnit(), CodeList.class);
			qp.setUnit(code==null?"":code.getValue());

			//第一次缓存
			if(com.chinaedu.oc.context.Context.isCacheProductLine) {
				productLineCacheServ.addCache();
				com.chinaedu.oc.context.Context.isCacheProductLine = false;
			}
			//转义产品线
			ProductLine productLine = productLineCacheServ.getProductLine(p.getProductLine());
			qp.setProductLine(productLine==null?"":productLine.getName());

			//转义地区
			List<ProductArea> list = out.getListProductArea().get(p.getId());
			if(list != null && list.size()>=1) {
				List<String> area = new ArrayList<>();
				for(ProductArea pa : list) {
					Area a = cacheServ.queryData(Constant.AREA_DATA, pa.getAreaId(), Area.class);
					area.add(a==null?"":a.getName());
				}
				qp.setArea(area);
			}
			data.add(qp);
		}
		vo.setRecordsTotal(out.getTotals()+"");
		vo.setRecordsFiltered(out.getTotals()+"");
		vo.setData(data);
		vo.setStatus(Constant.TRUE);

		return vo;
	}

	/**
	 * 导出
	 * @Description: TODO
	 * @param @param productQuery
	 * @param @param response
	 * @param @throws HttpRequestException
	 * @return void    返回类型
	 * @throws
	 */
	@RequestMapping("/export")
	@ResponseBody
	public void export(ProductQuery productQuery, HttpServletResponse response, HttpServletRequest request) throws HttpRequestException{
		CommonListVo<QueryProduct> out = this.query(productQuery, null, null, request);
		ExcelCreater<QueryProduct> csv = new ExcelCreater<>();
		String date = new SimpleDateFormat(Constant.DATE).format(new Date());
		try {
			csv.createExcel(out.getData(),
					new String[] {"code", "name", "schoolSystem", "schoolLevel", "timeLength", "grade",
							"specialty", "productLine", "productType",
							"expiryDate", "expiryLength", "billType", "businessType","uploadDate","unit"},
					new String[] {"编码", "名称", "学制", "学段", "时长", "年级",
							"学科", "产品线", "产品类型",
							"有效日期", "有效期", "支付方式", "业务类型", "上报日期", "单位"},
					"产品信息导出"+date,
					response,request);
		}catch (Exception e) {
			e.printStackTrace();
		}

	}

	/**
	 * 审核
	 * @Description: TODO
	 * @param @param id
	 * @param @param request
	 * @param @return
	 * @param @throws HttpRequestException
	 * @return PubOutputDto    返回类型
	 * @throws
	 */
	@RequestMapping("/review")
	@ResponseBody
	public PubOutputDto review(String id, HttpServletRequest request) throws HttpRequestException {

		ProductInput input = new ProductInput();
		input.setProductId(id);
		input.setToCommodityType(Constant.INSERT);
		ManageUser userLogin= (ManageUser) request.getSession().getAttribute(Session.manageUserLogin.name());
		input.setUser(userLogin.getUserId());
		//审核
		PubOutputDto out = HttpHelper.sendRequest(IName.Product.REVIEW_PRODUCT, input, PubOutputDto.class);
		if(Constant.FALSE == out.getStatus()) {
			return out;
		}
		//推送
		out = HttpHelper.sendRequest(IName.Product.TO_COMMODITY_PRODUCT, input, PubOutputDto.class);
		if(Constant.FALSE == out.getStatus()) {
			out.setMsg("审核成功，但是推送到商品失败");
			return out;
		}
		return out;
	}
}
